package com.ruoyi.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.ZhuanjiaDept;
import com.ruoyi.system.service.IZhuanjiaDeptService;
import com.ruoyi.system.tools.BooleanMessage;
import com.ruoyi.web.controller.tool.JsonResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Dept;
import com.ruoyi.system.service.IDeptService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 单位信息Controller
 * 
 * @author dy
 * @date 2024-05-27
 */
@Controller
@RequestMapping("/system/deptxinxi")
public class DeptController extends BaseController
{
    private String prefix = "system/deptxinxi";

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IZhuanjiaDeptService zhuanjiaDeptService;

    @RequiresPermissions("system:deptxinxi:view")
    @GetMapping()
    public String dept()
    {
        return prefix + "/dept";
    }

    /**
     * 查询单位信息列表
     */
    @RequiresPermissions("system:deptxinxi:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Dept dept)
    {
        startPage();
        List<Dept> list = deptService.selectDeptList(dept);
        return getDataTable(list);
    }

    /**
     * 导出单位信息列表
     */
    @RequiresPermissions("system:deptxinxi:export")
    @Log(title = "单位信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Dept dept)
    {
        List<Dept> list = deptService.selectDeptList(dept);
        ExcelUtil<Dept> util = new ExcelUtil<Dept>(Dept.class);
        return util.exportExcel(list, "单位信息数据");
    }

    /**
     * 新增单位信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存单位信息
     */
    @RequiresPermissions("system:deptxinxi:add")
    @Log(title = "单位信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Dept dept)
    {
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改单位信息
     */
    @RequiresPermissions("system:deptxinxi:edit")
    @GetMapping("/edit/{deptid}")
    public String edit(@PathVariable("deptid") String deptid, ModelMap mmap)
    {
        Dept dept = deptService.selectDeptByDeptid(deptid);
        mmap.put("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 修改保存单位信息
     */
    @RequiresPermissions("system:deptxinxi:edit")
    @Log(title = "单位信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Dept dept)
    {
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除单位信息
     */
    @RequiresPermissions("system:deptxinxi:remove")
    @Log(title = "单位信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(deptService.deleteDeptByDeptids(ids));
    }

    /**
    * 查询单位列表
    */
    @PostMapping("/customlist")
    @ResponseBody
    public JsonResult<?> customlist(Dept dept){
        List<Map<String,Object>> list = deptService.CustomList(dept);
        return JsonResult.getSuccessResult(list);
    }

    @PostMapping("/subdeptlist")
    @ResponseBody
    public JsonResult<?> subdeptlist(String deptid){
        List<Dept> list = deptService.findSubDept(deptid);
        return JsonResult.getSuccessResult(list);
    }

    @PostMapping("/customone")
    @ResponseBody
    public JsonResult<?> customone(String deptid){
        Map<String,Object> dept = deptService.CustomOne(deptid);
        return JsonResult.getSuccessResult(dept);
    }

    /**
     *查询单位所有层级联系方式
    */
    /**
     * 专家管理-查询统计-单位联系方式
     */
    @PostMapping("/findLianxifangshi")
    @ResponseBody
    public JsonResult<?> findLianxifangshi(String deptid)
    {
        try {
            List<Map<String,Object>> map = deptService.selectLianxifangshi(deptid);
            return JsonResult.getSuccessResult(map);
        } catch (Exception e) {
            logger.error("deptxinxi -> findLianxifangshi: "+e.getMessage());
            return JsonResult.getErrorResult("查询专家管理-查询统计-单位联系方式");
        }
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult<?> save(Dept dept, HttpServletRequest request){
        try {
            String mmDeptId = dept.getDeptid();

            int isOk = 0;

            if (mmDeptId==null||mmDeptId.equals("")){
                dept.setDeptid(UUID.randomUUID().toString());
                dept.setStatus((long)1);

                isOk = deptService.insertDept(dept);
            }else if(mmDeptId!=null){

                HttpSession session = request.getSession();

//                CustomLog mmLog = new CustomLog();
//                mmLog.setId(UUID.randomUUID().toString());
//                mmLog.setCaozuoleixing("单位信息修改");
//                mmLog.setCaozuorenid(session.getAttribute("userid").toString());
//                mmLog.setCaozuoren(session.getAttribute("username").toString());
//                mmLog.setDanweiid(session.getAttribute("deptid").toString());
//                mmLog.setDanweimingcheng(session.getAttribute("deptname").toString());
//                mmLog.setCaozuoriqi(new Date());
//                mmLog.setCaozuoshuoming("修改单位信息");
//                mmLog.setIsvalid((long)1);

                isOk = deptService.updateDept(dept);

                //写入自定义日志
//                customLogService.insertCustomLog(mmLog);
            }

            return isOk==1?JsonResult.getSuccessResult("保存成功"):JsonResult.getErrorResult("保存失败");
        } catch (Exception e) {
            logger.error("deptxinxi -> save: "+e.getMessage());
            return JsonResult.getErrorResult("修改单位失败");
        }
    }

    @PostMapping("/zhuxiao")
    @ResponseBody
    public JsonResult<?> zhuxiao(@RequestParam("deptid")String ppDeptId){
        try {

            Map<String,Object> mmMap = new HashMap<>();

            //这里的单位ID为旧单位ID
            Dept mmDept = deptService.selectDeptByDeptid(ppDeptId);
            if (mmDept==null){
                return JsonResult.getErrorResult("该单位不存在");
            }

            ZhuanjiaDept zhuanjiaDept = new ZhuanjiaDept();
            zhuanjiaDept.setDeptid(ppDeptId);
            zhuanjiaDept.setStatus("1");
            List<ZhuanjiaDept> mmDeptZhuanjiaList = zhuanjiaDeptService.selectZhuanjiaDeptList(zhuanjiaDept);
            if (!mmDeptZhuanjiaList.isEmpty()){
                mmMap.put("code","a");
                mmMap.put("msg","该单位中专家还未全部转移至其他单位，无法注销");
                return JsonResult.getSuccessResult(mmMap);
            }

            Dept mmDept2 = new Dept();
            mmDept2.setParentid(ppDeptId);
            List<Dept> mmDeptList = deptService.selectDeptList(mmDept2);
            if (!mmDeptList.isEmpty()){
                mmMap.put("code","b");
                mmMap.put("msg","该单位存在下属单位，无法注销");
                return JsonResult.getSuccessResult(mmMap);
            }

            mmDept.setStatus(2l);
            int modifyOK = deptService.updateDept(mmDept);

            mmMap.put("code","c");
            mmMap.put("msg","注销成功");

            return modifyOK==1?JsonResult.getSuccessResult(mmMap):JsonResult.getErrorResult("注销失败");
        } catch (Exception e) {
            logger.error("deptxinxi -> zhuxiao: "+e.getMessage());
            return JsonResult.getErrorResult("注销单位失败");
        }
    }

    /**
     * 检查单位必要信息是否填写
     */
    @GetMapping("/checkDeptInfo")
    @ResponseBody
    public JsonResult<?> checkDeptInfo()
    {
        try {
            BooleanMessage bm = deptService.checkDeptInfo(getUserId());
            return JsonResult.getSuccessResult(bm);
        } catch (Exception e) {
            logger.error("deptdetail -> checkDeptInfo: "+e.getMessage());
            return JsonResult.getErrorResult("检查单位必要信息是否填写失败");
        }
    }



}
